<template>
  <div :data-id="data.id"></div>
  <!-- <Selected v-if="selected" :data="data" /> -->
</template>

<script lang="ts" setup>
import { useStageStore } from '@/store/stage';
import { Mode } from '@/views/editor/scene/types';
import { cloneDeep } from 'lodash';

interface IProps {
  data: any;
}
const props = withDefaults(defineProps<IProps>(), { data: { id: '' } });

const mode = inject('mode') as Mode;
const isEditMode = mode === 'edit';

const { cimInstance } = window;
const mounted = ref(false);
const stageStore = useStageStore();
const zoomConfig = { range: 200, heading: (45 / 180) * Math.PI, pitch: (-30 / 180) * Math.PI };

const L00 = [1.234709620475769, 1.221461296081543, 1.273156881332397];
const L1_1 = [1.135921120643616, 1.171217799186707, 1.287644743919373];
const L10 = [1.245193719863892, 1.245591878890991, 1.282818794250488];
const L11 = [-1.106930732727051, -1.112522482872009, -1.153198838233948];
const L2_2 = [-1.086226940155029, -1.079731941223145, -1.101912498474121];
const L2_1 = [1.189834713935852, 1.185906887054443, 1.214385271072388];
const L20 = [0.01778045296669, 0.02013735473156, 0.025313569232821];
const L21 = [-1.086826920509338, -1.084611177444458, -1.111204028129578];
const L22 = [-0.05241484940052, -0.048303380608559, -0.041960217058659];

const selected = computed(() => stageStore.layerId === props.data.id);

const render = () => {
  try {
    const { data, ...restData } = props.data;
    const rotation = data.rotation;
    const scale = data.isScale ? new Array(3).fill(data.scaleAll) : data.scale;
    const position = data.positions[0];
    const layerData = {
      ...restData,
      ...data,
      name: restData.id,
      positions: data.positions,
      rotation,
      scale,
      pose: {
        position,
        rotation,
        scale,
      },
      color:
        data.opacity === 100
          ? data.color
          : `${data.color}${Math.round((data.opacity * 255) / 100)
              .toString(16)
              .padStart(2, '0')}`,
    };
    layerData.readyCall = () => {
      stageStore.layerLoadedIdList.push(restData.id);
      if (isEditMode && stageStore.layerId === props.data.id) {
        cimInstance.api.removeLoading();
      }
      if (data.show && stageStore.layerId === props.data.id) {
        cimInstance.api.virtualModel({
          layerNames: [restData.id],
          color: [1, 1, 1, 1],
          enabled: true,
          outlinewidth: 3,
          visibleEdgeColor: '#0331d6',
          showGlow: true,
          edgeGlow: 0.3,
        });
        layerLocation(layerData);
      }
    };
    console.log(999, cloneDeep(layerData), cloneDeep(props.data), stageStore.layerId);
    if (mounted.value) {
      cimInstance.api.updateLayerGraphics(layerData.id, {
        ...layerData,
        iblConfig:
          data.ImageURL && data.isImage
            ? {
                environmentMaps: '/res/' + data.ImageURL,
              }
            : {},
      });
      updateMaterial();
    } else {
      if (isEditMode && stageStore.layerId === props.data.id) {
        // 模型占位符
        cimInstance.api.addLoading({
          position,
          url: '/cimup/statics/model/model-loading.glb',
          flyTo: false,
        });
      }
      // 真正的模型
      cimInstance.api.addLayerByType({
        ...layerData,
        iblConfig:
          data.ImageURL && data.isImage
            ? {
                coefficients: [L00, L1_1, L10, L11, L2_2, L2_1, L20, L21, L22],
                environmentMaps: '/res/' + data.ImageURL,
              }
            : {},
      });
      mounted.value = true;
    }
  } catch (error) {
    console.log(error);
  }
};

function layerLocation(layer: any) {
  cimInstance.api.zoomToLayer(layer.id, zoomConfig);
}

const updateMaterial = () => {
  if (stageStore.layerData.material.length > 0) {
    const {
      layerData: { material },
    } = stageStore;
    const oldVal = cimInstance.api.getMaterialListByLayer(stageStore?.layerId);
    for (let index = 0; index < material.length; index++) {
      const item = material[index];
      const oldItem = oldVal?.[index];
      if (!item || !oldItem) {
        continue;
      }
      if (
        item.metallic !== oldItem.metallic ||
        item.roughness !== oldItem.roughness ||
        item.textureUrl !== oldItem.textureUrl
      ) {
        cimInstance.api.updateMaterialInfo(stageStore?.layerId, { ...item });
      }
    }
  }
};

watch(
  () => stageStore.layerId,
  (val) => {
    if (val === props.data.id) {
      layerLocation(stageStore.layerData);
      cimInstance.api.virtualModel({
        layerNames: [props.data.id],
        color: [1, 1, 1, 1],
        enabled: true,
        outlinewidth: 3,
        visibleEdgeColor: '#0331d6',
        showGlow: true,
        edgeGlow: 0.3,
      });
    } else {
      if (stageStore.layerData?.type !== 'GLTFMODEL') {
        cimInstance.api.virtualModel({});
      }
    }
  }
);

watch(props.data, render, { deep: true, immediate: true });

onUnmounted(() => {
  cimInstance.api.destroyLayer(props.data.id);
});
</script>

<style lang="less" scoped></style>
